﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Android.App;
using Android.Content;
using Android.Content.PM;
using Android.Graphics;
using Android.Graphics.Drawables;
using Android.OS;
using Android.Support.Design.Widget;
using Android.Support.V4.App;
using Android.Support.V4.View;
using Android.Support.V4.Widget;
using Android.Support.V7.App;
using Android.Support.V7.Widget;
using Android.Util;
using Android.Views;
using Android.Widget;
using Com.Gcssloop.Widget;
using FFImageLoading;
using mb;
using mb.Droid;

using GridLayout = Android.Support.V7.Widget.GridLayout;

namespace libmp
{
    public class CategoryView
    {
        public static MyFragment CreateFragment()
        {
            return new MyFragment()
            {
                Title = "分类",
                    MyOnCreateView = (f, container) =>
                    {
                        return new CategoryView(f).CreateView(container);
                    }
            };
        }

        static StartActivity activity = StartActivity.This;
        MyFragment myFragment { get; }
        ViewGroup childFragmentContainer;
        CategoryView(MyFragment f)
        {
            myFragment = f;
            myFragment.dict.Add("owner", this);
        }

        View CreateView(ViewGroup container)
        {
            childFragmentContainer = new FrameLayout(activity);
            childFragmentContainer.Id = View.GenerateViewId();
            childFragmentContainer.LayoutParameters = new ViewGroup.LayoutParams(-1, -1);
            childFragmentContainer.SetBackgroundColor(Color.YellowGreen);

            Push(new CategoryListView(this).CreateFragment());
            return childFragmentContainer;
        }

        public void Push(MyFragment frag)
        {
            // var fragMgr = activity.SupportFragmentManager;
            var fragMgr = myFragment.ChildFragmentManager;
            var fragTransaction = fragMgr.BeginTransaction();
            fragTransaction.Replace(childFragmentContainer.Id, frag, "category-push");
            fragTransaction.AddToBackStack("push");
            fragTransaction.Commit();
        }

        public void Pop()
        {
            myFragment.ChildFragmentManager.PopBackStack();
        }

        public void ReClick()
        {
            App.logger.Log("reclick me", myFragment.ChildFragmentManager.Fragments.Count, myFragment.ChildFragmentManager.BackStackEntryCount);
            if (myFragment.ChildFragmentManager.BackStackEntryCount > 1)
            {
                Pop();
            }
        }
    }
    class CategoryListView : BaseMixList<DataStore.VideoCategory>
    {

        MyFragment myFragment;
        CategoryView parent;
        LinearLayout rootLayout;
        public CategoryListView(CategoryView parent)
        {
            this.parent = parent;
        }

        public MyFragment CreateFragment()
        {
            var frag = new MyFragment()
            {
                MyOnCreateView = (f, container) =>
                {
                    return CreateView();
                },
            };
            myFragment = frag;
            return frag;
        }

        public View CreateView()
        {
            if (rootLayout == null)
            {
                rootLayout = new LinearLayout(activity);
                rootLayout.Orientation = Orientation.Vertical;
                rootLayout.SetBackgroundColor(Util.MainBKColor);
                rootLayout.FillParent();
                rootLayout.AddView(CreateTitleBar());

                dataSource = DataStore.store.GetVideoCategory();

                insertItems.Add(new InsertItem()
                {
                    insertBefore = 0,
                        height = 120,
                        view = CreateSearchView(),
                });

                int margin = 20;
                int height = Util.dpToPx(160);
                int vheight = height - margin * 2;
                insertItems.Add(new InsertItem()
                {
                    insertBefore = 0,
                        height = height,
                        view = new AdImageView(3, 4).CreateView().SetLayoutParam(new LinearLayout.LayoutParams(-1, vheight) { TopMargin = margin, LeftMargin = margin, RightMargin = margin, })
                });

                Setup();
                Reload();

                rootLayout.AddView(GetListView());
            }

            return rootLayout;
        }

        View CreateSearchView()
        {
            var adveriseLayout = new LinearLayout(activity);
            adveriseLayout.SetBackgroundColor(Color.Rgb(246, 247, 251));
            adveriseLayout.Orientation = Orientation.Vertical;
            adveriseLayout.LayoutParameters = new ViewGroup.LayoutParams(-1, -1);

            LinearLayout searchLayout = new LinearLayout(activity);
            searchLayout.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 80)
            {
                LeftMargin = 30,
                RightMargin = 30,
                TopMargin = 30,
            };
            searchLayout.Orientation = Orientation.Horizontal;

            LinearLayout searchLeftLayout = new LinearLayout(activity);
            searchLeftLayout.LayoutParameters = new LinearLayout.LayoutParams(900, LinearLayout.LayoutParams.MatchParent);
            searchLeftLayout.SetVerticalGravity(GravityFlags.CenterVertical);
            searchLeftLayout.SetBackgroundColor(Color.White);

            RCRelativeLayout searchLeftRCLayout = new RCRelativeLayout(activity);
            var searchLeftRCLayoutParams = new LinearLayout.LayoutParams(900, LinearLayout.LayoutParams.MatchParent);
            searchLeftRCLayout.LayoutParameters = searchLeftRCLayoutParams;
            searchLeftRCLayout.SetRadius(40);
            searchLeftRCLayout.AddView(searchLeftLayout);
            searchLayout.AddView(searchLeftRCLayout);

            var searchImage = new ImageView(activity);
            var searchImageParams = new LinearLayout.LayoutParams(60, ViewGroup.LayoutParams.MatchParent);
            searchImageParams.LeftMargin = 30;
            searchImage.LayoutParameters = searchImageParams;
            searchImage.SetImageDrawable(Util.DrawableFromFile("search/ask_02.png"));
            searchLeftLayout.AddView(searchImage);

            var searchText = new EditText(activity);
            var searchTextParams = new LinearLayout.LayoutParams(0, ViewGroup.LayoutParams.MatchParent, 1);
            searchTextParams.RightMargin = 45;
            searchText.LayoutParameters = searchTextParams;
            searchText.Focusable = true;
            searchText.Background = null;
            searchText.Hint = "手机模玩,展览演出";
            searchText.SetSingleLine();
            searchText.SetPadding(0, 2, 0, 0);
            searchText.SetTextSize(ComplexUnitType.Pt, 7);
            searchText.SetTextColor(Color.Rgb(105, 105, 105));
            searchText.ImeOptions = Android.Views.InputMethods.ImeAction.Search;
            searchText.EditorAction += (s, e) =>
            {
                if (e.ActionId == Android.Views.InputMethods.ImeAction.Search)
                {
                    e.Handled = true;
                    Util.HideKeyboard(searchText);
                    SearchResultView.OpenSearchResult(searchText.Text);
                }
            };
            searchLeftLayout.AddView(searchText);

            var searchRightImage = new ImageView(activity);
            searchRightImage.LayoutParameters = new LinearLayout.LayoutParams(70, ViewGroup.LayoutParams.MatchParent)
            {
                LeftMargin = 40,
            };
            searchRightImage.SetImageDrawable(Util.DrawableFromFile("category/Shaixuan.png"));
            searchLayout.AddView(searchRightImage);

            adveriseLayout.AddView(searchLayout);

            return adveriseLayout;
        }

        View CreateTitleBar()
        {
            var titleLayout = new LinearLayout(activity);
            titleLayout.SetBackgroundColor(Util.MainColor);
            titleLayout.LayoutParameters = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MatchParent, 160);
            titleLayout.Orientation = Orientation.Horizontal;
            titleLayout.SetGravity(GravityFlags.Center);

            var titleText = new TextView(activity) { Text = "分类" };

            // titleText.Tag = 3;

            titleLayout.AddView(titleText);
            titleText.SetTextColor(Color.White);
            titleText.SetTextSize(ComplexUnitType.Pt, 9);
            return titleLayout;
        }

        protected override View CreateCell(Dictionary<string, object> viewData)
        {
            var squareLayout = new MySquareLayout(activity, 0.5f);
            var rcl = new RCRelativeLayout(activity);
            rcl.SetRadius(20);
            rcl.ClipBackground = true;
            rcl.StrokeColor = Color.Rgb(90, 90, 90);
            rcl.StrokeWidth = 1;
            rcl.SetBackgroundColor(Color.White);
            var lp = new FrameLayout.LayoutParams(-1, -1);
            lp.SetMargins(20, 10, 20, 10);
            squareLayout.AddView(rcl, lp);

            var tv = new TextView(activity);
            tv.LayoutParameters = new FrameLayout.LayoutParams(-1, -1);
            tv.TextAlignment = TextAlignment.Center;
            tv.Gravity = GravityFlags.Center;
            tv.SetTextColor(Color.Black);
            rcl.AddView(tv);
            viewData.Add("text", tv);

            squareLayout.Click += (s, e) =>
            {
                int p = this.recyclerView.GetChildAdapterPosition(squareLayout);
                int idx = GetDataIndex(p);
                SelectItem(idx);

            };
            return squareLayout;
        }
        protected override void UpdateCell(View cell, int p, Dictionary<string, object> viewData)
        {
            int idx = GetDataIndex(p);
            // logger.Log("updatecell", p, idx);
            var tv = viewData["text"] as TextView;
            tv.Text = dataSource[idx].catename;
        }

        void SelectItem(int idx)
        {
            logger.Log("click", idx);

            // fragment.ChildFragmentManager
            parent.Push(new CategoryMovieListView(dataSource[idx].vcateid, idx).CreateFragment());
        }
    };

    class CategoryMovieListView : ExMovieList
    {
        public MyFragment CreateFragment()
        {
            myFragment = new MyFragment()
            {
                MyOnCreateView = (f, container) =>
                {
                    return CreateView();
                },
            };
            return myFragment;
        }

        MyFragment myFragment;
        int categoryId;
        int selectIdx;
        public CategoryMovieListView(int categoryId, int idx)
        {
            this.categoryId = categoryId;
            this.selectIdx = idx;
        }

        public View CreateView()
        {
            LinearLayout layout = new LinearLayout(activity);
            layout.Orientation = Orientation.Vertical;
            layout.SetBackgroundColor(Util.MainBKColor);
            layout.FillParent();
            layout.AddView(CreateTitleBar());
            layout.AddView(new LinearLayout(activity) { LayoutParameters = new ViewGroup.LayoutParams(-1, 10) });

            dataSource = DataStore.store.GetVideoForCateID(this.categoryId);

            Setup();
            Reload();

            layout.AddView(GetListView());
            return layout;
        }

        View CreateTitleBar()
        {
            LinearLayout titleBarFLayout = new LinearLayout(activity);
            titleBarFLayout.Orientation = Orientation.Vertical;
            titleBarFLayout.SetBackgroundColor(Color.Rgb(238, 238, 238));

            LinearLayout LayoutTop = new LinearLayout(activity);
            LayoutTop.LayoutParameters = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MatchParent, 120);
            LayoutTop.SetGravity(GravityFlags.Center);
            LayoutTop.SetBackgroundColor(Color.Rgb(251, 114, 153));

            LinearLayout LayoutTopLeft = new LinearLayout(activity);
            var LayoutTopLeftParams = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            LayoutTopLeft.LayoutParameters = LayoutTopLeftParams;
            LayoutTopLeft.SetVerticalGravity(GravityFlags.CenterVertical);
            var returnImageView = new ImageView(activity);
            returnImageView.SetImageDrawable(Util.DrawableFromFile("user/Fanhui.png"));
            var returnImageViewParams = new LinearLayout.LayoutParams(40, 40);
            returnImageViewParams.LeftMargin = 10;
            returnImageViewParams.RightMargin = 30;
            returnImageView.LayoutParameters = returnImageViewParams;
            LayoutTopLeft.AddView(returnImageView);

            var returnText = new TextView(activity);
            returnText.Text = "返回";
            returnText.SetTextColor(Color.White);
            returnText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            returnText.SetTextSize(ComplexUnitType.Pt, 7);
            LayoutTopLeft.AddView(returnText);
            LayoutTop.AddView(LayoutTopLeft);
            LayoutTopLeft.Click += (s, e) =>
            {
                logger.Log("返回------------");
                var parentFrag = myFragment.ParentFragment as MyFragment;
                parentFrag.GetUserData<CategoryView>("owner")?.Pop();
            };

            LinearLayout LayoutTopCenter = new LinearLayout(activity);
            LayoutTopCenter.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            LayoutTopCenter.SetGravity(GravityFlags.Center);
            var topCenterText = new TextView(activity);
            topCenterText.Text = DataStore.store.GetVideoCategory() [this.selectIdx].catename;
            topCenterText.SetTextColor(Color.White);
            topCenterText.SetTypeface(Typeface.Default, TypefaceStyle.Bold);
            topCenterText.SetTextSize(ComplexUnitType.Pt, 9);
            LayoutTopCenter.AddView(topCenterText);
            LayoutTop.AddView(LayoutTopCenter);

            LinearLayout LayoutTopRight = new LinearLayout(activity);
            LayoutTopRight.LayoutParameters = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.MatchParent, 1);
            LayoutTopRight.SetGravity(GravityFlags.Center);
            LayoutTop.AddView(LayoutTopRight);
            titleBarFLayout.AddView(LayoutTop);

            return titleBarFLayout;
        }
    };

}